var GeneratorId = require('../utils/generator-id.js')();
var DeepCopy = require('../utils/deepcopy.js');
var Engine = function() {
	/**
	 * class运时期的栈模型
	 */
	var CurrentClass = (function() {
		var vClasses = new Array();
		var setStateClass;
		return {
			getCurrent: function() {
				return vClasses[vClasses.length - 1] || {
					props: {},
					refs: {}
				};
			},
			setCurrent: function(cls) {
				vClasses.push(cls);
			},
			removeCurrent: function() {
				return vClasses.pop();
			},
			setCurrentState: function(cls) {
				setStateClass = cls;
			},
			getCurrentState: function() {
				return setStateClass;
			}
		}
	})();

	return {
		/**
		 *  创建React的class对象
		 * @param {Object} cfg 对象配置项
		 */
		createClass: function(cfg) {
			var _f = function(props) {
				var config = {}; //必须要创建一个新的对象，解决同一个组件多次实例化的情况。
				config.componentDidMount = function() {};
				for(var key in cfg) {
					config[key] = cfg[key];
				}
				config.props = {};
				config.state = {};
				config.setState = function(state,fn) {
					this.state = DeepCopy.copy(this.state, state);
					this.forceUpdate(fn);
				};
				config.realDomDidUpdate = function() {
					if(this.componentDidUpdate != undefined && typeof(this.componentDidUpdate) === 'function') {
						this.componentDidUpdate();
					}
					if(window.IS_IN_IE7) {
						UcsIconFontForIe7.process();
					}
				}
				config.forceUpdate = function(fn) {
					this.refs = {};
					CurrentClass.setCurrent(this);
					CurrentClass.setCurrentState(this);
					var _node = this.render();
					CurrentClass.setCurrentState(null);
					this.realDOM.parentElement.replaceChild(_node, this.realDOM);
					this.realDOM = _node;
                    setTimeout(function checkMount() {
                        if(config.realDOM.ownerDocument.body.contains(config.realDOM)) {
                            fn && fn();
                        } else {
                            setTimeout(checkMount, 50);
                        }
                    }, 50);
                    if(window.IS_IN_IE7) {
                        UcsIconFontForIe7.process();
                    }
				};
				//创建初始化的props
				if(config.getDefaultProps != undefined &&
					typeof(config.getDefaultProps) === 'function') {
					config.props = config.getDefaultProps();
				}
				//传入参数
				for(var key in props) {
					config.props[key] = props[key];
				}
				config.refs = {};
				config.props.children = [];
				//监听DOM加载事件
				config.realDOMDidMount = function() {
					//元素非node结点的，不需要进行加载检查事件，直接返回
					if(config.realDOM.ownerDocument == undefined) {
						return;
					}
					setTimeout(function checkMount() {
						if(config.realDOM.ownerDocument.body.contains(config.realDOM)) {
							config.componentDidMount();
							if(window.IS_IN_IE7) {
								UcsIconFontForIe7.process();
							}
						} else {
							setTimeout(checkMount, 50);
						}
					}, 50);
				}
				CurrentClass.setCurrent(config);
				return config;
			}
			return _f;
		},
		/**
		 * 创建React的Element元素
		 */
		createElement: function() {
			var tagName = arguments[0];
			var props = arguments[1] || {};
			if(typeof(tagName) == 'string') {
				var _node = document.createElement(tagName);
				for(var key in props) {
					this.setDomAttribute(_node, key, props[key]);
				}
				var childrenLength = arguments.length - 2;
				if(childrenLength === 1) {
					if(arguments[2] != undefined) {
						this.appendChildDOM(_node, arguments[2]);
					}
				} else if(childrenLength > 1) {
					for(var index = 2; index < arguments.length; index++) {
						if(arguments[index] != undefined) {
							this.appendChildDOM(_node, arguments[index], true);
						}
					}
				}
				this.dataBind(_node, props);
				return _node;
			} else {
				var children = [];
				for(var index = 2; index < arguments.length; index++) {
					var param = arguments[index];
					if(param && typeof param === 'object' &&
						Array == param.constructor) {
						children = children.concat(param);
					} else {
						children.push(param);
					}
				}
				var vDom = tagName(props); //创建Class。
				vDom.props.children = children;
				//创建初始化的state
				if(vDom.getInitialState != undefined &&
					typeof(vDom.getInitialState) === 'function') {
					vDom.state = vDom.getInitialState();
				}
				var _node = vDom.render();
				//解决组件嵌套组件的问题
				while(this.checkNodeType(_node, 'realDOM')) {
					_node = _node.realDOM;
				}
				vDom.realDOM = _node;
//				if(!CurrentClass.getCurrentState()){
					vDom.realDOMDidMount();
//				}
				CurrentClass.removeCurrent(); //render完成，清理队列。
				if(props != undefined && props["ref"] != undefined) {
					CurrentClass.getCurrent().refs[props["ref"]] = vDom;
				}
				return vDom;
			}
		},
		/**
		 *  设置DOM的属性
		 * @param {Object} _node
		 * @param {Object} key
		 * @param {Object} value
		 */
		setDomAttribute: function(_node, key, value) {
            if(key == 'children' || key == 'label' || key == 'dmbind' || key == ''){
                return;
            }
			if(key.indexOf("on") == 0) {
				var fn = value;
				if(fn != undefined) {
					if(typeof(fn) !== 'function') {
						fn = new Function(fn);
					}
					EventListener.addEventHandler(_node, key.toLowerCase(), fn.bind(CurrentClass.getCurrent()));
				}
			} else if(key == 'className') {
				_node.className = value; //不能使用setAttribute("class","xx"),在IE7以下会有问题
			} else if(key == 'style') {
				var inlineStyle = value;
				for(var skey in inlineStyle) {
					_node.style[skey] = inlineStyle[skey]; //不能使用setAttribute("style","xx"),在IE7以下会有问题
				}
			} else if(key == 'ref') {
				CurrentClass.getCurrent().refs[value] = _node;
			} else if(key == 'For') {
				_node.setAttribute('for', value);
			} else if(key == 'checked') {
				if(value === true) {
					_node.setAttribute(key, value);
					_node.setAttribute('defaultChecked', true); //兼容IE浏览器
				}else{
					_node.removeAttribute(key);
					_node.removeAttribute('defaultChecked');
				}
			} else if(key == 'disabled') {
				if(value === true) {
					_node.setAttribute(key, value);
				}else{
					_node.removeAttribute(key);
				}
			} else {
				_node.setAttribute(key, value);
			}
		},
		/**
		 *  克隆元素的方法
		 * @param {Object} _ele
		 * @param {Object} cfg
		 */
		cloneElement: function(_ele, cfg) {
			if(this.checkNodeType(_ele, 'realDOM')) {
				for(var key in cfg) {
					_ele.props[key] = cfg[key];
				}
				_ele.realDOM = _ele.render();
			} else {
				for(var key in cfg) {
					this.setDomAttribute(_ele, key, cfg[key]);
				}
			}
			return _ele;
		},
		/**
		 *  支持批量使用this.props
		 */
		__spread: function() {
			var props = {};
			for(var i = 0; i < arguments.length; i++) {
				var param = arguments[i];
				if(param && typeof param === 'object' &&
					Array == param.constructor) {
					for(var j = 0; j < param.length; j++) {
						var subparam = param[i];
						for(var key in subparam) {
							props[key] = subparam[key]
						}
					}

				} else {
					for(var key in param) {
						props[key] = param[key]
					}
				}
			}
			return props;
		},
		/**
		 * 检查节点类型
		 * @param {Object} _node
		 * @param {Object} relation
		 */
		checkNodeType: function(_node, relation) {
			if('hasOwnProperty' in _node) {
				return _node.hasOwnProperty(relation);
			} else {
				return Object.prototype.hasOwnProperty(_node, relation);
			}
		},

		/**
		 * 处理数据绑定
		 * @param {Object} _node
		 * @param {Object} props
		 */
		dataBind: function(_node, props) {
			var dmbind = CurrentClass.getCurrent().props.dmbind || props['dmbind'];
			if(dmbind != undefined) {
				EventListener.addEventHandler(_node, 'onchange', function(e) {
					var event = e || window.event;
					var target = event.target || event.srcElement;
					var value = target.value;
					if(target.type == 'checkbox'){
						value = target.checked;
					}
					UEventHub.emit(dmbind + UI_EVENT_CONST.SET_UI_VALUE_EVENT, value);
				});
				UEventHub.on(dmbind + UI_EVENT_CONST.SET_UDM_VALUE_EVENT, function(v) {
					_node.value = v;
				});

                if(_node.nodeName == 'SPAN'||_node.nodeName == 'A'||_node.nodeName == 'BUTTON'){
                    return ;
                }else {
                    EventListener.addEventHandler(_node, 'onblur', function(e) {
                        var event = e || window.event;
                        var target = event.target || event.srcElement;
                        UEventHub.emit(dmbind + UI_EVENT_CONST.ONBLUR_EVENT, target.value);
                    });
                }
			}
		},
		/**
		 *  追加实体子结点
		 * @param {Object} _node 父结点
		 * @param {Object} child 子结点
		 * @param {Object} isWrap 字符串是否用span嵌套，默认为false
		 */
		appendChildDOM: function(_node, child, isWrap) {
			if(child != undefined) {
				var _tmpArray = [].concat(child);
				for(var i = 0; i < _tmpArray.length; i++) {
					if(_tmpArray[i].realDOM && 1 === _tmpArray[i].realDOM.nodeType) {
						_node.appendChild(_tmpArray[i].realDOM);
					} else {
						if(_tmpArray[i] && 1 === _tmpArray[i].nodeType) {
							_node.appendChild(_tmpArray[i]);
						} else {
							if(isWrap) {
								var _span = document.createElement('span');
								_span.innerHTML = _tmpArray[i];
								_node.appendChild(_span);
							} else {
								_node.innerHTML = _tmpArray[i];
							}
						}
					}
				}
			}
		}
	}
}

/**
 * 为了使用JSX语法，自建一个仿React的类
 */
module.exports = Engine;